document.addEventListener('DOMContentLoaded', () => {
  const captureBtn = document.getElementById('captureBtn');
  const statusDiv = document.getElementById('status');

  async function injectContentScriptIfNeeded(tab) {
    try {
      await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        files: ['content.js']
      });
    } catch (e) {
      console.log('Content script may already be injected:', e);
    }
  }

  captureBtn.addEventListener('click', async () => {
    statusDiv.textContent = '正在截图...';
    captureBtn.disabled = true;

    try {
      // 获取当前标签页
      const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
      if (!tab) {
        throw new Error('无法获取当前标签页');
      }

      // 确保content script已注入
      await injectContentScriptIfNeeded(tab);

      // 发送消息给content script
      const response = await chrome.tabs.sendMessage(tab.id, {action: 'capture'});
      console.log('Received response:', response);

      if (response && response.imageData) {
        // 下载图片
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
        const filename = `webpage-${timestamp}.png`;

        await chrome.downloads.download({
          url: response.imageData,
          filename: filename,
          saveAs: true
        });

        statusDiv.textContent = '截图完成！';
      } else {
        throw new Error('未收到截图数据');
      }
    } catch (error) {
      console.error('Error:', error);
      statusDiv.textContent = `错误: ${error.message || '截图失败，请重试'}`;
    } finally {
      captureBtn.disabled = false;
    }
  });
});

